﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;
using MossmanMill.DataModel;
using System.Globalization;
using System.Threading;
using MossmanMill.Controller;

namespace MossmanMill.View
{
    /// <summary>
    /// Excel Data Import Form class that import excel data into database
    /// </summary>
    /// <remarks>
    /// This class is thread safe. 
    /// </remarks>
    /// <dates>
    /// 15/05/2012 - created by Chiaki Sato
    /// </dates>
    public partial class ImportForm : Form
    {
        // Background Worker Thread Result
        private const string WORKER_THREAD_RESULT_SUCCESS = "SUCCESS";
        private const string WORKER_THREAD_RESULT_ERROR_FILE_IO = "FILE_IO_ERROR";
        private const string WORKER_THREAD_RESULT_ERROR_OTHER = "OTHER_ERROR";

        // Messages
        private const string MESSAGE_IMPORT_SUCCESS = "Data was successfully imported.";
        private const string MESSAGE_DELETE_ALL_DATA = "Do you really want to delete all table data from MCM database?";

        // Error Messages
        private const string ERROR_MESSAGE_FILE_NOT_FOUND = "The file could not be found. Check the spelling of the file name, and verify that the file location is correct.";
        private const string ERROR_MESSAGE_IMPORT_FAILED = "Import was failed. Check whether database is online.";

        // Import Messagebox Title
        private const string TITLE_MCM_IMPORT = "MCM Import";
        private const string TITLE_ERROR_MESSAGE = "MCM Import Error";

        // File Dialog Box
        private const string FILE_DIALOG_FIELE_NAME = "C200 IO Listing .xlsx";
        private const string FILE_DIALOG_DIRECTORY = @"";
        private const string FILE_DIALOG_FILTER = "Excel Files(*.xlsx;*.xls)|*.xlsx;*.xls|All Files(*.*)|*.*";
        private const string FILE_DIALOG_TITLE = "Open MCM Import Excel File";

        //MainForm reference, for refreshing data
        private MainForm parent;

        /// <summary>
        /// Constructor for Import form class. 
        /// </summary>
        public ImportForm(MainForm parent)
        {
            InitializeComponent();
            this.parent = parent;
        }

        /// <summary>
        /// Import button click event hander. 
        /// </summary>
        /// <param name="sender">event sender</param>
        /// <param name="e">event arguments</param>
        private void ButtonImport_Click(object sender, EventArgs e)
        {
            ButtonImport.Enabled = false;
            ButtonClose.Enabled = false;

            // Background Worker Tread Start
            BackgroundWorkerImport.RunWorkerAsync();            
        }

        /// <summary>
        /// Close button click event hander. 
        /// </summary>
        /// <param name="sender">event sender</param>
        /// <param name="e">event arguments</param>
        private void ButtonClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// File Dialog Box button click event hander. 
        /// </summary>
        /// <param name="sender">event sender</param>
        /// <param name="e">event arguments</param>
        private void ButtonFileDialog_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.FileName = FILE_DIALOG_FIELE_NAME;
            ofd.InitialDirectory = FILE_DIALOG_DIRECTORY;
            ofd.Filter = FILE_DIALOG_FILTER;
            ofd.FilterIndex = 1;    // select Excel Files
            ofd.Title = FILE_DIALOG_TITLE;
            ofd.RestoreDirectory = true;
            ofd.CheckFileExists = true;
            ofd.CheckPathExists = true;

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                textBoxExcelFileDir.Text = ofd.FileName;
            }
        }

        /// <summary>
        /// Back ground worker thread for import. 
        /// This method run on a different threat from other methods in this class.
        /// </summary>
        /// <param name="sender">parent sender thread</param>
        /// <param name="e">event arguments</param>
        private void BackgroundWorkerImport_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker senderWorkerThread = (BackgroundWorker)sender;

            senderWorkerThread.ReportProgress(0);       // 0% progress to start

            try
            {
                textBoxExcelFileDir.Text.Trim();
                string excelFileName = textBoxExcelFileDir.Text.Trim();

                // Create Import Manager by Factory
                IImportFactory importFactory = new ImportFactory();
                IImportManager importManager = importFactory.Make(ImportFactory.CLASS_TYPE_IMPORT, excelFileName);

                importManager.EquipmentDataImport(senderWorkerThread);
                importManager.RoomRackDataImport(senderWorkerThread);

                senderWorkerThread.ReportProgress(100);       // 100% progress to complete

                e.Result = WORKER_THREAD_RESULT_SUCCESS;

            }
            catch (COMException ex)
            {
                e.Result = WORKER_THREAD_RESULT_ERROR_FILE_IO;
                Console.WriteLine(MethodBase.GetCurrentMethod().Name + ": " + ex.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(MethodBase.GetCurrentMethod().Name + ": " + ex.ToString());
                e.Result = WORKER_THREAD_RESULT_ERROR_OTHER;
            }

        }

        /// <summary>
        /// Change notification from the back ground worker thread for import. 
        /// </summary>
        /// <param name="sender">Parent sender thread</param>
        /// <param name="e">Progress changed event arguments</param>
        private void BackgroundWorkerImport_RunWorkerChangeded(object sender, ProgressChangedEventArgs e)
        {

            LabelProgress.Text = e.ProgressPercentage + "% complete.";
            ProgressBarImport.Value = e.ProgressPercentage;
        }

        /// <summary>
        /// Complete notification from the back ground worker thread for import. 
        /// </summary>
        /// <param name="sender">parent sender thread</param>
        /// <param name="e">Run worker complete event arguments</param>
        /// <summary>
        private void BackgroundWorkerImport_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Result.Equals(WORKER_THREAD_RESULT_SUCCESS))
            {

                MessageBox.Show(MESSAGE_IMPORT_SUCCESS, TITLE_MCM_IMPORT, MessageBoxButtons.OK);
            }
            else if (e.Result.Equals(WORKER_THREAD_RESULT_ERROR_FILE_IO))
            {
                MessageBox.Show(ERROR_MESSAGE_FILE_NOT_FOUND, TITLE_ERROR_MESSAGE, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show(ERROR_MESSAGE_IMPORT_FAILED, TITLE_ERROR_MESSAGE, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            ButtonImport.Enabled = true;
            ButtonClose.Enabled = true;
            //Refresh Main Form data
            parent.Init();
        }

        private void ButtonDeleteAll_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show(MESSAGE_DELETE_ALL_DATA, TITLE_MCM_IMPORT, MessageBoxButtons.OKCancel,MessageBoxIcon.Warning);

            if (dialogResult == DialogResult.OK)
            {
                // Create Import Manager by Factory
                IImportFactory importFactory = new ImportFactory();
                IImportManager importManager = importFactory.Make(ImportFactory.CLASS_TYPE_IMPORT, "");

                this.Cursor = Cursors.WaitCursor;

                importManager.DeleteAllTableData();

                this.Cursor = Cursors.Default;

            }
            //Refresh Main Form data
            parent.Init();
        }
    
    }

}
